﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.Video;

public class VideoItem : MonoBehaviour
{

    private VideoPlayer mVideoPlayer;
    private RenderTexture renderTexture;
    private Slider mSlider;
    private Slider volumeSlider;
    private RawImage mPlayImg;
    private bool isDown;

    private Action startFunc = null;//开始回调
    private Action endFunc = null;//结束回调
    private bool activeVideo = false;

    public bool IsPlaying
    {
        get
        {
            return mVideoPlayer.isPlaying;
        }
    }

    public double curTime;
    public double allTime;


    /// <summary>
    /// 开始回调
    /// </summary>
    /// <param name="_startFunc"></param>
    /// <returns></returns>
    public VideoItem SetStartFunc(Action _startFunc)
    {
        this.startFunc = _startFunc;
        return this;
    }

    /// <summary>
    /// 结束回调
    /// </summary>
    /// <param name="_startFunc"></param>
    /// <returns></returns>
    public VideoItem SetEndFunc(Action _endFunc)
    {
        this.endFunc = _endFunc;
        return this;
    }

    public VideoItem SetRenderTexture(int width, int hight)
    {
        renderTexture = new RenderTexture(width, hight, 1);
        renderTexture.name = "MovieTexture";
        renderTexture.dimension = UnityEngine.Rendering.TextureDimension.Tex2D;
        return this;
    }

    /// <summary>
    /// 设置进度条
    /// </summary>
    public VideoItem SetSlider(Slider slider)
    {
        mSlider = slider;
        //mSlider.onValueChanged.AddListener((value) =>
        //{
        //    if (mVideoPlayer.isPaused)
        //        SetVideoTimeValueChange();
        //});
        EventTrigger sliderTrigger = mSlider.gameObject.AddComponent<EventTrigger>();
        EventTrigger.Entry pointStart = new EventTrigger.Entry();
        pointStart.eventID = EventTriggerType.PointerDown;
        pointStart.callback.AddListener(SliderBeginDrag);
        EventTrigger.Entry pointEnd = new EventTrigger.Entry();
        pointEnd.eventID = EventTriggerType.PointerUp;
        pointEnd.callback.AddListener(SliderEndDrag);
        sliderTrigger.triggers.Add(pointStart);
        sliderTrigger.triggers.Add(pointEnd);
        //mSlider.onValueChanged.AddListener((value) =>
        //{
        //    if (isDown)
        //        SetVideoTimeValueChange();
        //});
        return this;
    }

    /// <summary>
    /// 设置音量条
    /// </summary>
    public VideoItem SetVolumeSlider(Slider _volumeSlider)
    {
        volumeSlider = _volumeSlider;
        volumeSlider.onValueChanged.AddListener((value) =>
        {
            mVideoPlayer.SetDirectAudioVolume(0, value);
        });
        return this;
    }

    /// <summary>
    /// 设置播放UI
    /// </summary>
    /// <param name="rawImage"></param>
    public VideoItem SetPlayeImg(RawImage rawImage)
    {
        mPlayImg = rawImage;
        mPlayImg.texture = renderTexture;
        return this;
    }

    /// <summary>
    /// 设置播放源
    /// </summary>
    /// <param name="videoSource"></param>
    /// <returns></returns>
    public VideoItem SetPlaySource(VideoSource videoSource)
    {
        mVideoPlayer.source = videoSource;
        return this;
    }

    /// <summary>
    /// 设置播放URL
    /// </summary>
    /// <returns></returns>
    public VideoItem SetPlayUrl(string url)
    {
        Debug.Log(url);
        mVideoPlayer.url = url;
        return this;
    }

    /// <summary>
    /// 设置播放片段
    /// </summary>
    /// <returns></returns>
    public VideoItem SetPlayClip(VideoClip clip)
    {
        mVideoPlayer.clip = clip;
        return this;
    }

    /// <summary>
    /// 设置循环播放
    /// </summary>
    /// <param name="isLoop"></param>
    public VideoItem SetLoop(bool isLoop)
    {
        mVideoPlayer.isLooping = isLoop;
        return this;
    }

    /// <summary>
    /// 创造视频播放插件
    /// </summary>
    public VideoItem CreateVideoPlayer(int width, int height)
    {
        if (mVideoPlayer == null)
        {
            if(!gameObject.GetComponent<VideoPlayer>())
                mVideoPlayer = gameObject.AddComponent<VideoPlayer>();
            mVideoPlayer.playOnAwake = false;
            renderTexture = new RenderTexture(width, height, 1);
            renderTexture.name = "MovieTexture";
            renderTexture.dimension = UnityEngine.Rendering.TextureDimension.Tex2D;
            mVideoPlayer.targetTexture = renderTexture;
            mVideoPlayer.prepareCompleted += (vp) =>
            {
                startFunc?.Invoke();
            };
            mVideoPlayer.loopPointReached += (vp) =>
            {
                endFunc?.Invoke();
                //Debug.Log("mVideoPlayer.time= " + mVideoPlayer.time);
                //Debug.Log("mVideoPlayer.length= " + mVideoPlayer.length);
                //if (mVideoPlayer.time != 0 && mVideoPlayer.length != 0)
                //{
                //    CancelInvoke();
                //    Stop();
                //    mPlayImg.color = Color.black;
                //}
                //else if (mVideoPlayer.time == 0)
                //{
                //    Play();
                //}
            };
        }
        return this;
    }

    private void SliderBeginDrag(BaseEventData data)
    {
        CancelInvoke();
        StopAllCoroutines();
        //InitVideoPlayer();
        mVideoPlayer.Pause();
        isDown = true;
        SetVideoTimeValueChange();
    }

    /// <summary>
    /// 给 Slider 添加结束拖拽事件
    /// </summary>
    /// <param name="eventData"></param>
    private void SliderEndDrag(BaseEventData data)
    {
        CancelInvoke();
        StopAllCoroutines();
        StartCoroutine("EndDrag");
    }

    IEnumerator EndDrag()
    {
        yield return new WaitForSeconds(0.25f);

        SetVideoTimeValueChange();
        isDown = false;
        if (mVideoPlayer.time != mVideoPlayer.length)
        {
            Invoke("Play", 0.75f);
        }
    }

    // Start is called before the first frame update
    void Awake()
    {
        //CreateVideoPlayer(Screen.width, Screen.height);
    }

    /// <summary>
    /// 开始播放
    /// </summary>
    public void Play()
    {
        //mVideoPlayer.waitForFirstFrame = true;
        //if (isRePlay)
        //{
        //    mVideoPlayer.Pause();
        //    mVideoPlayer.time = 0;
        //    mVideoPlayer.frame = 0;
        //}
        if (activeVideo)
            StartCoroutine("RPlay");
        else
        {
            Debug.Log("没激活,不播放视频");
        }
    }

    public void ActiveVideo(bool b)
    {
        activeVideo = b;
    }

    /// <summary>
    /// 暂停播放
    /// </summary>
    public void Pause()
    {
        mVideoPlayer.Pause();
    }

    private IEnumerator RPlay()
    {
        yield return new WaitForEndOfFrame();
        mVideoPlayer.Play();
        yield return new WaitForSeconds(0.05f);
        mPlayImg.color = Color.white;
    }

    private void SetVideoTimeValueChange()
    {
        mVideoPlayer.time = mSlider.value * mVideoPlayer.length;
    }

    private void InitVideoPlayer()
    {
        if (mVideoPlayer == null)
        {
            CreateVideoPlayer(Screen.width, Screen.height);
        }
    }



    // Update is called once per frame
    void Update()
    {
        if (mVideoPlayer != null)
        {
            curTime = mVideoPlayer.time;
            if(mVideoPlayer.length != 0)
                allTime = mVideoPlayer.length;
            if (mVideoPlayer.isPlaying && mSlider != null && isDown == false)
            {
                mSlider.value = (float)(mVideoPlayer.time / mVideoPlayer.length) + 0.0000141f;

                //mVideoPlayer.loopPointReached

            }
                
            //else
            //    SetVideoTimeValueChange();
        }
    }

    /// <summary>
    /// 停止播放
    /// </summary>
    public void Stop()
    {
        mVideoPlayer.Stop();
        mPlayImg.color = Color.black;

    }

    /// <summary>
    /// 快进
    /// </summary>
    public void FastForward()
    {
        if (mVideoPlayer != null && mVideoPlayer.length != 0)
        {
            if (mVideoPlayer.time + 15 >= mVideoPlayer.length)
                mVideoPlayer.time = mVideoPlayer.length;
            else
                mVideoPlayer.time += 15;
            Debug.Log(mVideoPlayer.time);
            StartCoroutine(SetPlaySliderValue());
        }
    }

    /// <summary>
    /// 回退
    /// </summary>
    public void FallBack()
    {
        if (mVideoPlayer != null && mVideoPlayer.length != 0)
        {
            if (mVideoPlayer.time - 15 > 0)
                mVideoPlayer.time -= 15;
            else
                mVideoPlayer.time = 0;
            StartCoroutine(SetPlaySliderValue());
        }
    }

    private IEnumerator SetPlaySliderValue()
    {
        yield return new WaitForSeconds(0.25f);
        mSlider.value = (float)(mVideoPlayer.time / mVideoPlayer.length) + 0.0000141f;
        Debug.LogWarning("111  mSlider.value = " + mSlider.value);
        Debug.LogWarning("mVideoPlayer.time = " + mVideoPlayer.time);
        Debug.LogWarning("mVideoPlayer.length = " + mVideoPlayer.length);
    }
}
